package dm71.espil.REST;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import dm71.espil.AeSimpleSHA1;
import dm71.espil.CurrentUser;
import dm71.espil.models.Highscore;
import dm71.espil.models.PendingRequest;
import dm71.espil.models.User;

import android.R.bool;
import android.util.Xml.Encoding;

/**
 * TODO Put here a description of what this class does.
 * 
 * @author mah. Created Dec 12, 2011.
 */
public class DataService
{
	public final String Root = "http://espil.maltebaden.com/ESpilService/";

	//Progress working
	public boolean Login(String username, String password)
	{
		try
		{
			URI address = new URI(Root + "login");
			RestClient client = new RestClient(address.toString());
			client.AddParam("username", username);

			String hashedPassword = AeSimpleSHA1.SHA1(password);
			client.AddParam("password", hashedPassword);

			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject jsonObject = new JSONObject(json);
			int userID = jsonObject.getInt("LogInResult");

			if (userID > 0)
			{
				CurrentUser.Instance().LogIn(new User(userID));
				return true;
			}

			return false;

		} catch (URISyntaxException exception)
		{
			// TODO Auto-generated catch-block stub.
			exception.printStackTrace();
		} catch (Exception exception)
		{
			// TODO Auto-generated catch-block stub.
			exception.printStackTrace();
		}

		return false;
	}

	public boolean CreateUser(String username, String password, String name,
			String lastname, String cLass)
	{
		try
		{
			URI address = new URI(Root + "create");
			RestClient client = new RestClient(address.toString());
			client.AddParam("username", username);
			String hashedPassword = AeSimpleSHA1.SHA1(password);
			client.AddParam("password", hashedPassword);
			client.AddParam("name", name);
			client.AddParam("lastName", lastname);
			client.AddParam("cLass", cLass);

			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject jsonObject = new JSONObject(json);

			return jsonObject.getBoolean("CreateUserResult");

		} catch (URISyntaxException exception)
		{
			exception.printStackTrace();
		} catch (Exception exception)
		{
			exception.printStackTrace();
		}
		return false;
	}
	
	public boolean IsFriend(int userID, int friendID)
	{
		try
		{
			URI address = new URI(Root + "isFriend");
			RestClient client = new RestClient(address.toString());
			client.AddParam("userID", String.valueOf(userID));
			client.AddParam("friendID", String.valueOf(friendID));
			
			client.Execute(RequestMethod.GET);
			
			String result = client.getResponse();
			JSONObject obj = new JSONObject(result);
			
			return obj.getBoolean("IsFriendResult");
		}
		catch (URISyntaxException exception)
		{
			exception.printStackTrace();
		} catch (Exception exception)
		{
			exception.printStackTrace();
		}
		return false;
	}
	
	public boolean BefriendUser(int userID, int friendID)
	{
		try
		{
			URI address = new URI(Root + "befrienduser");
			RestClient client = new RestClient(address.toString());
			client.AddParam("userID", String.valueOf(userID));
			client.AddParam("friendID", String.valueOf(friendID));
		
			client.Execute(RequestMethod.GET);
		}
		catch (URISyntaxException exception)
		{
			exception.printStackTrace();
		} catch (Exception exception)
		{
			exception.printStackTrace();
		}
		return false;
	}

	public boolean EditUser(int userID, String username, String password,
			String name, String lastname, String cLass)
	{
		try
		{
			URI address = new URI(Root + "edituser");
			RestClient client = new RestClient(address.toString());
			client.AddParam("userID", String.valueOf(userID));
			client.AddParam("username", username);
			client.AddParam("password", password);
			client.AddParam("name", name);
			client.AddParam("lastName", lastname);
			client.AddParam("cLass", cLass);

			client.Execute(RequestMethod.GET);
		} catch (URISyntaxException exception)
		{
			exception.printStackTrace();
		} catch (Exception exception)
		{
			exception.printStackTrace();
		}
		return false;
	}

	public User Request(int userID)
	{
		try
		{
			URI address = new URI(Root + "request");
			RestClient client = new RestClient(address.toString());
			int userid = CurrentUser.Instance().GetUser().UserID;
			client.AddParam("userID", String.valueOf(userid));

			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject wrapper = new JSONObject(json);
			JSONObject obj = wrapper.getJSONObject("GetUserResult");
			User user = new User(obj);

			return user;
		}

		catch (URISyntaxException exception)
		{
			exception.printStackTrace();
		} catch (Exception exception)
		{
			exception.printStackTrace();
		}
		return null;
	}

	public void CreateHighscore(int score)
	{
		try
		{
			URI address = new URI(Root + "highscore");
			RestClient client = new RestClient(address.toString());

			if (CurrentUser.Instance().IsAuthenticated())
			{
				int userID = CurrentUser.Instance().GetUser().getUserID();
				client.AddParam("userID", String.valueOf(userID));
				client.AddParam("score", String.valueOf(score));
				client.Execute(RequestMethod.GET);
			}

		} catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public User[] getFriends()
	{
		ArrayList<User> users = new ArrayList<User>();

		try
		{
			URI address = new URI(Root + "getAllFriends");
			RestClient client = new RestClient(address.toString());

			int userID = CurrentUser.Instance().GetUser().getUserID();
			client.AddParam("userID", String.valueOf(userID));
			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject object = new JSONObject(json);

			JSONArray highscoreArray = object
					.getJSONArray("GetAllFriendsResult");

			for (int i = 0; i < highscoreArray.length(); i++)
			{
				JSONObject newUser = highscoreArray.getJSONObject(i);
				User user = new User(newUser);
				users.add(user);
			}

		} catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		User[] userArray = new User[users.size()];
		return users.toArray(userArray);
	}
	
	public User[] getAllUsers(String query)
	{
		ArrayList<User> users = new ArrayList<User>();

		try
		{
			URI address = new URI(Root + "getAllUsers");
			RestClient client = new RestClient(address.toString());

			int userID = CurrentUser.Instance().GetUser().getUserID();
			client.AddParam("userID", String.valueOf(userID));
			client.AddParam("q", query);
			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject object = new JSONObject(json);

			JSONArray userArray = object.getJSONArray("GetAllUsersResult");

			for (int i = 0; i < userArray.length(); i++)
			{
				JSONObject newUser = userArray.getJSONObject(i);
				User user = new User(newUser);
				users.add(user);
			}
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		User[] userArray = new User[users.size()];
		return users.toArray(userArray);
	}

	public Highscore[] GetHighscores(int count)
	{
		ArrayList<Highscore> highscores = new ArrayList<Highscore>();

		try
		{
			URI address = new URI(Root + "highscores");
			RestClient client = new RestClient(address.toString());

			int userID = CurrentUser.Instance().GetUser().getUserID();
			client.AddParam("count", String.valueOf(count));
			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject object = new JSONObject(json);
			JSONArray highscoreArray = object
					.getJSONArray("GetHighscoresResult");

			for (int i = 0; i < highscoreArray.length(); i++)
			{
				JSONObject jsonObject = highscoreArray.getJSONObject(i);
				Highscore highscore = new Highscore(jsonObject);
				highscores.add(highscore);
			}

		} catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Highscore[] array = new Highscore[highscores.size()];
		return highscores.toArray(array);
	}

	public PendingRequest[] GetPendingInvites()
	{
		ArrayList<PendingRequest> pending = new ArrayList<PendingRequest>();

		try
		{
			URI address = new URI(Root + "getpendinginvites");
			RestClient client = new RestClient(address.toString());

			int userID = CurrentUser.Instance().GetUser().UserID;
			client.AddParam("userID", String.valueOf(userID));
			
			client.Execute(RequestMethod.GET);

			String json = client.getResponse();
			JSONObject object = new JSONObject(json);
			JSONArray pendingArray = object.getJSONArray("GetPendingInvitesResult");

			for (int i = 0; i < pendingArray.length(); i++)
			{
				JSONObject jsonObject = pendingArray.getJSONObject(i);
				PendingRequest pendingInvite = new PendingRequest(jsonObject);
				pending.add(pendingInvite);
			}

		} 
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		PendingRequest[] array = new PendingRequest[pending.size()];
		return pending.toArray(array);
	}
	
	public void AcceptFriendRequest(int friendID)
	{
		try
		{
			URI address = new URI(Root + "acceptfriendinvite");
			RestClient client = new RestClient(address.toString());

			if (CurrentUser.Instance().IsAuthenticated())
			{
				int userID = CurrentUser.Instance().GetUser().getUserID();
				client.AddParam("userID", String.valueOf(friendID));
				client.AddParam("friendID", String.valueOf(userID));
				client.Execute(RequestMethod.GET);
			}
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void Unfriend(int friendID)
	{
		try
		{
			URI address = new URI(Root + "unfriend");
			RestClient client = new RestClient(address.toString());

			if (CurrentUser.Instance().IsAuthenticated())
			{
				int userID = CurrentUser.Instance().GetUser().getUserID();
				client.AddParam("userID", String.valueOf(userID));
				client.AddParam("friendID", String.valueOf(friendID));
				client.Execute(RequestMethod.GET);
			}
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
